package cn.max.client;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.max.client.utils.EncodingUtil;

/**
 *@author Val.(Valentine Vincent) E-mail:valer@126.com
 *@version 1.0
 *@date 2012-6-21
 *Instruction : 
 **/
public class Response implements Closeable {
	
	private InputStream is;
	private HttpURLConnection conn;
	private Map<String, String> headers = new HashMap<String, String>();
	
	public Response(InputStream is, HttpURLConnection conn) {
		this.is = is;
		this.conn = conn;
		
		for (int i = 0;; i++) {
			String headerName = conn.getHeaderFieldKey(i);
			String headerValue = conn.getHeaderField(i);
			if (headerName == null && headerValue == null) {
				break;
			}
			
			headers.put(headerName, headerValue);
		}
	}
	
	public int getCode() {
		try {
			return conn.getResponseCode();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return -1;
	}
	
	public Set<String> getHeaders() {
		return headers.keySet();
	}
	
	public String getHeader(String key) {
		return headers.get(key);
	}
	
	public InputStream getAsStream() {
		return is;
	}
	
	public String getAsString() {
		return getAsString("UTF-8");
	}
	
	public String getAsString(String charset) {
		try {
			return EncodingUtil.getStringFromStream(is, charset);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public void close() {
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		conn.disconnect();
	}
	
}
